import ViewUI from 'view-design';

/**
 * 接口状态码处理
 * Created by kahn on 2018/10/15.
 */
const codeArray = {
    'success': "200",//请求成功
    'accountInvalid': '434',//token被其他端登录导致失效
    'tokenInvalid': '400',//token失效
};
//状态码处理和执行回调
const dealCode = (options = {}) => {
    let _options = {
        code: '',
        successCallback: () => {},//正常业务回调
        accountInvalidCb: () => {},//账号登录有误
        tokenInvalidCb: () => {},//token失效回调
        errorDeal: () => {},//异常业务回调
        completeDeal: () => {}//所有业务处理完毕回调
    }
    let config = Object.assign(_options, options);

    //判断是否传了状态码
    if(!config.code) {
        console.log('接口返回码未传');
        return;
    }
    //判断接收的状态码是否存在codeArray中
    // if(!isInCodeArray(config.code)) {
    //     console.log('接口返回码本地不存在，或者未做处理');
    //     return;
    // }

    switch(config.code)
    {
    case codeArray.success:
        if(config.successCallback && typeof config.successCallback === 'function') {
            config.completeDeal();
            config.successCallback();
        }else {
            console.log('请添加successCallback参数');
        }
        break;
    case codeArray.accountInvalid:
        if(config.accountInvalidCb && typeof config.accountInvalidCb === 'function') {
            config.completeDeal();
            config.accountInvalidCb();
        }else {
            console.log('请添加successCallback参数');
        }
        break;
    case codeArray.tokenInvalid:
        window.localStorage.clear();
        window.sessionStorage.clear();
        ViewUI.Spin.hide();
        ViewUI.Modal.error({
            title: '提示',
            content: '用户没有登录或者登录失效！',
            okText: '重新登录',
            onOk: () => {
                window.location.href = '/login';
            }
        });
        break;
    default:
        config.completeDeal();
        config.errorDeal();
        break;
    }
};

//判断状态码是否在cdoeArray里面
const isInCodeArray = o => {
    for(var i in codeArray){
        if (o == parseInt(codeArray[i])) {
            return true;
        };
    }
    return false;
}

export { dealCode }